/**
 * 
 */
package com.novartis.nims.trialsubmitter;

import java.io.File;
import java.net.URI;

/**
 * @author Josh Snyder
 *
 */
public class SortedTrialReader extends TrialReader {

	/**
	 * @param ts
	 * @param resource
	 */
	public SortedTrialReader(TrialSubmitter ts, URI trialLocation) {
		super(ts, trialLocation);
	}

	/* (non-Javadoc)
	 * @see com.novartis.nims.trialsubmitter.TrialReader#initialize()
	 */
	@Override
	protected void initialize() {
	}

	/* (non-Javadoc)
	 * @see com.novartis.nims.trialsubmitter.TrialReader#processFile(java.io.File, java.net.URI)
	 */
	@Override
	protected SubmissionKey processFile(File file, URI relativeLocation)
			throws TrialReaderException {
		String trialKey = null;
		String subjectKey = null;
		String visitKey = null;
		String visitNumber = null;
		String visitRepeatKey = null;
		String scanKey = null;
		String scanRepeatKey = null;

		String[] components = relativeLocation.getPath().split("/");

		if (components.length != 6) {
			throw new TrialReaderException("Input images are not sorted into a compatible directory structure.");
		}

		// determine clinical trial keys from directory names		
		trialKey = components[0];		
		subjectKey = components[1];
		
		StringBuilder parsedVisitName = new StringBuilder();
		StringBuilder parsedVisitNumber = new StringBuilder();
		StringBuilder parsedRepeatVisitNumber = new StringBuilder();
		if (! this.parseVisitString(components[2], parsedVisitName, parsedVisitNumber, parsedRepeatVisitNumber)) {
			throw new TrialReaderException(file.getAbsolutePath() + " does not have a valid visit directory name. " +
					"Try making sure the visit name, number and/or repeat number are present and separated " +
					"correctly.");
		}
		visitKey = parsedVisitName.toString();
		visitNumber = parsedVisitNumber.toString();
		visitRepeatKey = parsedRepeatVisitNumber.toString();
		visitRepeatKey = visitRepeatKey.isEmpty() ? "1" : visitRepeatKey;
		
		scanKey = components[3];
		scanRepeatKey = components[4];

		SubmissionKey fullKey = new SubmissionKey(
				trialKey,
				subjectKey,
				visitKey,
				visitRepeatKey,
				scanKey,
				scanRepeatKey);
		fullKey.setVisitNumber(visitNumber);

		return fullKey;
	}

}
